package com.googlecode.ddplan;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.lang.reflect.Method;
import java.text.ParseException;

import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.ScenarioType;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;

public class StateActionSteps {
	private Exception exception;
	private StateAction stateAction;
	private ValidationResult validation;

	@AfterScenario(uponType = ScenarioType.EXAMPLE)
	public void afterScenario() {
		exception = null;
		stateAction = null;
		validation = null;
	}

	@Given("I have a state $state for an action $action in class $klass")
	public void stateForActionInClass(String state, String action, String klass) throws ClassNotFoundException, SecurityException,
			NoSuchMethodException {
		Class<?> k = Class.forName(klass);
		Method actionMethod = null;
		for (Method m : k.getMethods()) {
			if (m.getName().equals(action)) {
				actionMethod = m;
				break;
			}
		}
		stateAction = new StateAction(state.replaceAll("'", ""), actionMethod);
	}

	@When("I parse $state")
	public void parse(@Named("state") String state) {
		try {
			StateAction stateAction = new StateAction(state.replaceAll("'", ""), Object.class.getMethods()[0]);
			stateAction.parse();
		} catch (Exception e) {
			exception = e;
		}
	}

	@When("the state get parsed and validated")
	@Given("the state get parsed and validated")
	public void parseAndValidate() throws ParseException {
		stateAction.parse();
		validation = stateAction.validate();
	}

	@Then("I have a message exception $message")
	public void messageException(@Named("message") String message) {
		if (exception == null) {
			assertEquals("no exception", message);
		} else {
			assertTrue(exception.getMessage().startsWith(message));
		}
	}

	@Then("I have no error validation")
	public void noErrorValidation() {
		assertTrue(validation.isValid());
	}
	
	@Then("I have an error validation $string")
	public void errorValidation(String string){
		assertTrue(!validation.isValid());
		assertTrue(validation.getErrors().contains(string.replaceAll("'", "")));
	}
}
